import { AllHTMLAttributes, createElement, type FC } from 'react';
import classNames from 'classnames';
import ButtonGroup from './ButtonGroup';
import { buttonDefaultProps } from './defaultProps';
import type { ButtonOptions } from './type';

export interface ButtonProps
  extends ButtonOptions,
    Omit<AllHTMLAttributes<HTMLElement>, 'as' | 'content' | 'color' | 'size' | 'type'> {}

interface ButtonInterface extends FC<ButtonProps> {
  Group: typeof ButtonGroup;
}

const Button: ButtonInterface = (props) => {
  const {
    className,
    as,
    active,
    disabled,
    basic,
    tertiary,
    inverted,
    color,
    content,
    loading,
    size,
    icon,
    fluid,
    type,
    children,
    forwardedRef,
    ...buttonProps
  } = props;

  return createElement(
    as!,
    {
      ref: forwardedRef,
      type: as === 'button' ? type : undefined,
      className: classNames(
        'ui',
        'button',
        color,
        size,
        loading,
        { active, disabled, basic, tertiary, inverted, loading, icon, fluid },
        className,
      ),
      ...buttonProps,
    },
    content ?? children,
  );
};

Button.displayName = 'Button';
Button.defaultProps = buttonDefaultProps;

Button.Group = ButtonGroup;

export default Button;
